#include "login.h"
#include "ui_login.h"


Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    ui->tedit_password->setEchoMode(QLineEdit::Password);

    //关联信号以及槽函数;
    connect(msgthread, msgthread->LoginRSP, this, &Login::DealLoginRSP);
    connect(msgthread, msgthread->RegistRSP, this, &Login::DealRegistRSP);
    //connect(MsgThread, &MsgThread::RegistRSP, this, &Login::DealRegistRSP);
}

Login::~Login()
{
    delete ui;
}

void Login::on_btn_login_clicked()
{
    //close调用了closeEvent
    QString user_name = ui->tedit_user->toPlainText();
    QString user_password = ui->tedit_password->text();
    if (user_name.isEmpty() || user_password.isEmpty()){
        QMessageBox::information(nullptr,
                                 "Login Faile",
                                 "user name or password can't empty");
    }else {
        QMessageBox::information(nullptr,
                                 "Login",
                                 "Send login message");
        TransMsg trans_msg;
        cout << "send msg" << endl;

        CreateReqLoginMsg(trans_msg, user_name.toStdString().c_str(), user_password.toStdString().c_str());
        // ShowTranslateMessage(trans_msg);
        send(send_client, (char *)&trans_msg, sizeof(TransMsg),0);
        //send(send_client, "fuck", 1024, 0);
    }
}

void Login::on_btn_register_clicked()
{
    QString user_name = ui->tedit_user->toPlainText();
    QString user_password = ui->tedit_password->text();
    if (user_name.isEmpty() || user_password.isEmpty()){
        QMessageBox::information(nullptr,
                                 "Regist Fail",
                                 "user name or password can't empty");
    }else {
        TransMsg trans_msg;
        CreateReqRegistMsg(trans_msg, user_name.toStdString().c_str(), user_password.toStdString().c_str());
        send(send_client, (char *)&trans_msg, sizeof(TransMsg),0);
//        SockSendMsg((char*)&trans_msg, send_client);
//        SockSendMsg(CreateReqRegistMsg(user_name.toStdString(), user_password.toStdString()), send_client);
    }
}

//用我的格式进行处理
void Login::DealLoginRSP(string ct){
    //TODO
    if (ct == "success"){
        this->close();
        Chat *win_chat = new Chat();
        win_chat->show();
    }else if (ct == "fail,password"){
        QMessageBox::information(nullptr, "Login Faile", "wrong password!");
    }else if (ct == "fail,nonexist"){
        QMessageBox::information(nullptr, "Login Faile", "Account logged in!");
    }else {
        QMessageBox::information(nullptr, "LoginError", ct.c_str());
    }
}

void Login::DealRegistRSP(string ct){
    if (ct == "success"){
        QMessageBox::information(nullptr, "Regist", "Regist Success!");
    }else if (ct == "fail"){
        QMessageBox::information(nullptr, "Regist", "Regist Fail,user already exist!");
    }else {
        QMessageBox::information(nullptr, "Regist", ct.c_str());
    }

}

